package com.gw.service.impl;

import com.gw.mapper.FileMapper;
import com.gw.pojo.entity.Bucket;
import com.gw.pojo.entity.File;
import com.gw.pojo.vo.FileVO;
import com.gw.service.FileService;
import com.gw.utils.MinioUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Autowired
    private FileMapper fileMapper;
    @Autowired
    private MinioUtil minioUtil;

    /**
     * 新建桶
     * @param bucketName
     */
    public void addBucket(String bucketName) {
        //查询桶列表，是否已存在
        Bucket bucket = fileMapper.getBucketByName(bucketName);
        if (bucket != null) {
            throw new RuntimeException("桶已存在，请勿重复创建！");
        }
        //创建桶
        fileMapper.addBucket(bucketName);
        minioUtil.makeBucket(bucketName);
    }

    /**
     * 查询桶列表
     * @return
     */
    public List<Bucket> getBuckets() {
        List<Bucket> list = fileMapper.getBuckets();
        return list;
    }

    /**
     * 删除桶
     * @param bucketName
     */
    public void removeBucket(String bucketName) {
        //从file表查询此桶内是否存在文件
        List<FileVO> list = fileMapper.getFilesByBucketName(bucketName);
        if (!list.isEmpty()){
            throw new RuntimeException("此桶内存在文件，不可删除");
        }
        //先从minio中删除
        minioUtil.removeBucket(bucketName);
        //从数据库中删除
        fileMapper.removeBucket(bucketName);
    }


    /**
     * 向指定桶添加文件
     * @param bucketName
     * @param multipartFile
     */
    public void uploadFile(String bucketName, MultipartFile multipartFile) {
        //获取文件的url
        String url = minioUtil.upload(multipartFile, bucketName);
        File file = File.builder()
                .fileName(multipartFile.getOriginalFilename())
                .fileUrl(url)
                .bucketName(bucketName)
                .build();
        //向数据库的files表插入数据
        fileMapper.addFile(file);
    }

    /**
     * 查询指定桶内所有文件
     * @param bucketName
     * @return
     */
    public List<FileVO> getFiles(String bucketName) {
        //检查此桶是否存在
        Bucket bucket = fileMapper.getBucketByName(bucketName);
        if (bucket == null){
            throw new RuntimeException("此桶不存在");
        }

        return fileMapper.getFilesByBucketName(bucketName);
    }


    /**
     * 下载文件
     * @param id
     * @return
     */
    public String downloadFile(Long id) {
        String url = fileMapper.getFileUrlById(id);
        if (url == null || url.isEmpty()){
            throw new RuntimeException("文件不存在");
        }
        return url;
    }


}
